#include "BlockQueue.hpp"
#include <ctime>
#include "Task.hpp"
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>

template <class C, class S>
class BlockQueues
{
public:
    BlockQueue<C> *c_bq;
    BlockQueue<S> *s_bq;
};

const std::string oper = "+-*/%";

void *consumer(void *bq_)
{
    // BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(bq_);
    BlockQueue<Task> *bq = (static_cast<BlockQueues<Task, SaveTask> *>(bq_))->c_bq;
    BlockQueue<SaveTask> *save_bq = (static_cast<BlockQueues<Task, SaveTask> *>(bq_))->s_bq;
    while (true)
    {
        // 消费活动
        // int data;
        Task t;
        // bq->pop(&data);
        bq->pop(&t);
        std::string result = t();
        // std::cout << "消费数据: " << t() << std::endl;
        std::cout << "消费任务: " << result << std::endl;

        // 存储任务
        // SaveTask save(result, Save);
        // save_bq->push(save);
        // std::cout << "推送保存任务完成...." << std::endl;

        // sleep(1);
    }
    return nullptr;
}

void *productor(void *bq_)
{
    // BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(bq_);
    BlockQueue<Task> *bq = (static_cast<BlockQueues<Task, SaveTask> *>(bq_))->c_bq;
    while (true)
    {
        // 生产活动
        // int data = rand() % 10; // 先用随机数，构建一个数据
        int x = rand() % 10;
        int y = rand() % 5;
        int operCode = rand() % oper.size();
        Task t(x, y, oper[operCode], mymath);
        bq->push(t);
        // std::cout << "生产数据：" << t() << std::endl;
        std::cout << "生产任务：" << t.toTaskString() << std::endl;
        sleep(1);
    }

    return nullptr;
}

void *saveTask(void *bq_)
{
    BlockQueue<SaveTask> *save_bq = (static_cast<BlockQueues<Task, SaveTask> *>(bq_))->s_bq;
    while (true)
    {
        SaveTask t;
        save_bq->pop(&t);
        t();
        std::cout << "保存任务完成...." << std::endl;
    }

    return nullptr;
}

int main()
{
    srand((unsigned long)time(nullptr) ^ getpid());
    // BlockQueue<int> *bq = new BlockQueue<int>(); // 阻塞队列
    // BlockQueue<Task> *bq = new BlockQueue<Task>(); // 阻塞队列
    BlockQueues<Task, SaveTask> bqs;
    bqs.c_bq = new BlockQueue<Task>();     // 阻塞队列
    bqs.s_bq = new BlockQueue<SaveTask>(); // 阻塞队列

    pthread_t c[2], p[3], save_thread;
    pthread_create(p, nullptr, productor, &bqs);     // 生产线程
    pthread_create(p + 1, nullptr, productor, &bqs); // 生产线程
    pthread_create(p + 2, nullptr, productor, &bqs); // 生产线程
    pthread_create(c, nullptr, consumer, &bqs);      // 消费线程
    pthread_create(c + 1, nullptr, consumer, &bqs);  // 消费线程
    // pthread_create(&save_thread, nullptr, saveTask, &bqs); // 保存线程

    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(p[2], nullptr);
    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    // pthread_join(save_thread, nullptr);

    delete bqs.c_bq;
    delete bqs.s_bq;

    return 0;
}